﻿using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class MagUserController : BaseController
    {
        private readonly MagUserBLL _bll = new MagUserBLL();
        private readonly MagUserRoleBLL _userRoleBll = new MagUserRoleBLL();

        #region 列表

        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult Listing(int draw, int start, int length)
        {
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            var direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "RoleName", "Mobile", "RealName", "UserN ame", "UserName" };
            var search = Request["search[value]"];
            var pageIndex = start / length + 1;

            var theList = _bll.GetPagingList(draw, pageIndex, length, SqlSafe(search),
                orderByColumns[order] + " " + direction);

            var jsonResult = Json(theList);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }

        #endregion

        #region 添加

        public ActionResult Create()
        {
            InitiSet();

            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection, MagUser model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var painPwd = model.Pwd;
            model.Pwd = EncryptionLib.Encrypt(painPwd);
            model.AddTime = DateTime.Now;
            model.IsSuper = 0;

            var result = _bll.Add(model);
            if (result <= 0) return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);

            if (!string.IsNullOrEmpty(model.Mobile))
            {
                var sendContent = string.Format(ConfigurationManager.AppSettings["MagSendContent"], model.UserName, painPwd);
                SmsRecordBLL.Instance.SendSms(model.Mobile, sendContent, CommonEnum.SmsRecordSendFrom.Mag, CommonEnum.SmsRecordUserActionSource.AddDelivery);
            }
            var magUserRole = MagUserRoleBLL.Instance.GetModelByUserId(result);
            if (magUserRole == null)
            {
                var urModel = new MagUserRole { UserId = result, RoleId = model.RoleId, IsDelete = false };
                var userRoleResult = _userRoleBll.Add(urModel);
            }
            else
            {
                magUserRole.RoleId = model.RoleId;
                _userRoleBll.Update(magUserRole);
            }

            if (result > 0) return RedirectToAction("List", "MagUser");

            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 修改

        public ActionResult Update(int? id)
        {
            InitiSet();

            var userId = 0;
            if (id == null || id <= 0)
            {
                userId = CurrentUser.Id;
                if (userId == 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            else
            {
                userId = (int)id;
            }

            var model = _bll.GetModel(userId);

            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.NotFound);

            ViewBag.CurrentUserRoleId = CurrentUser.RoleId;

            return View(model);
        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, MagUser model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var oriMagUser = _bll.GetModel(model.Id);
            model.Pwd = string.IsNullOrEmpty(model.Pwd) ? oriMagUser.Pwd : EncryptionLib.Encrypt(model.Pwd);

            var userResult = _bll.Update(model);
            //if (accountResult)
            //{
            //    //更改手机号或者密码，发送短信
            //    if (!string.IsNullOrEmpty(model.Mobile) && (!string.IsNullOrEmpty(model.Pwd)))
            //    {
            //        var sendContent = string.Format(ConfigurationManager.AppSettings["MagSendContent"], model.UserName, EncryptionLib.Decrypt(model.Pwd));
            //        SmsRecordBLL.Instance.SendSms(model.Mobile, sendContent, CommonEnum.SmsRecordSendFrom.Mag, CommonEnum.SmsRecordUserActionSource.ModifyDelivery);
            //    }
            //}

            var oriUserRole = _userRoleBll.GetModelByUserId(model.Id);
            oriUserRole.RoleId = model.RoleId;
            var userRoleResult = _userRoleBll.Update(oriUserRole);

            if (userResult && userRoleResult)
                return RedirectToAction("List", "MagUser");

            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 删除

        [HttpPost]
        public JsonResult Delete()
        {
            var ids = Request["doIds"];
            var result = _bll.DeleteList(ids);
            var accountRole = _userRoleBll.GetModelByUserId(int.Parse(ids));
            var arResult = _userRoleBll.DeleteList(accountRole.Id.ToString());

            return Json(result && arResult);
        }

        #endregion

        #region 账户唯一验证

        /// <summary>
        ///     检查重复数据
        /// </summary>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult ValidateUserName(string userName, int userId)
        {
            var resultMessage = _bll.CheckUserNameAvailable(userName, userId);
            return Json(resultMessage);
        }

        /// <summary>
        ///     检查重复数据
        /// </summary>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult ValidateMobile(string mobile, int userId)
        {
            var resultMessage = _bll.CheckMobileAvailable(mobile, userId);
            return Json(resultMessage);
        }

        #endregion

        #region Private Functions 自用函数

        private void InitiSet()
        {
            var lsRoles = MagRolesBLL.Instance.GetModelList().Select(model => new SelectListItem
            {
                Value = model.Id.ToString(),
                Text = model.Name
            }).ToList();
            ViewBag.Roles = lsRoles;
        }

        #endregion
    }
}